<?php
class mdl_account extends ujn_model {

	protected function __construct() {
		parent::__construct();
		$this->db_name		= '__' . GAME . '_common';
		$this->tbl_name		= __CLASS__;
		$this->_db			= $this->mysql('adam');
	}

	function makeAccount(mdl_object_remoteuserinfo $mao) {
		$suid = $mao->getPUid();
		$_sql = "insert into {$this->tbl_name} set `suid` = '$suid', `created` = " . NOW . ";";
		$this->_db->query($_sql);
		$newUID = $this->_db->insertID();

		// seve more
		mdl_field::getInstance()->makeUserInfo(
			$newUID,
			$mao->getName(),
			$mao->getNick(),
			$mao->getIcon(),
			$mao->getSex(),
			$mao->getFlds()
		);

		$this->setAccountOpt($uid, array(
			'last_update' => NOW
		));
		return $newUID;
	}

	function updateAccount($uid, mdl_object_remoteuserinfo $mao) {

		$this->setAccountOpt($uid, array(
			'is_needupdate' => '0',
			'last_update' => NOW
		));
		// seve more
		return mdl_field::getInstance()->updateUserInfo(
			$uid,
			$mao->getName(),
			$mao->getNick(),
			$mao->getIcon(),
			$mao->getSex(),
			$mao->getFlds()
		);
	}

	function getAccountOpt($uid) {
		$uck = mdl_ckey::getck(mdl_ckey::uopt_by_uid, $uid);

		$d = $_omc = $this->mc()->get($uck);
		return json_decode($d, true);
	}

	function setAccountOpt($uid, $opts = array()) {
		if(!is_array($opts) || count($opts) == 0)
			return false;

		$uck = mdl_ckey::getck(mdl_ckey::uopt_by_uid, $uid);
		$_omc = $this->mc();
		
		$uopt = $_omc->get($uck);
		if(!is_array($uopt)) $uopt = array();

		$uopt = array_merge($uopt, $opts);

		return $_omc->set($uck, json_encode($uopt), 0);
	}

	function getAccountSUIDByUID($uid) {

		$uck = mdl_ckey::getck(mdl_ckey::suid_by_uid, $uid);

		$_omc = $this->mc();
		$u_suid	= $_omc->get($uck);
		if(false == $u_suid || empty($u_suid)) {
			// query database;
			$_sql = "select `suid` from {$this->tbl_name} where `uid` = '$uid';";
			$data = $this->_db->getOne($_sql, MYSQL_ASSOC);
			$u_suid = isset($data['suid']) ? $data['suid'] : false;
			if(false != $u_suid) $_omc->set($uck, $u_suid, 0);
		}

		return $u_suid;
	}

	function getAccountUIDBySUID($suid) {

		$uck = mdl_ckey::getck(mdl_ckey::uid_by_suid, $suid);
		$_omc = $this->mc();
		
		$u_uid = $_omc->get($uck);
		if(false == $u_uid || empty($u_uid)) {
			// query database;
			$_sql = "select `uid` from {$this->tbl_name} where `suid` = '$suid';";
			$data = $this->_db->getOne($_sql, MYSQL_ASSOC);
			$u_uid = isset($data['uid']) ? $data['uid'] : 0;
			if(0 != $u_uid) $_omc->set($uck, $u_uid, 0);
		}

		return $u_uid;
	}

    /**
     * 单例模型
     * @return mdl_account
     */
	static function getInstance() {
        return parent::getInstance(__CLASS__);
	}
}